//
//  CharacterReadView.swift
//  WCHBLEApp
//
//  Created by 娟华 胡 on 2021/3/24.
//

import UIKit

class CharacterReadView: UIView {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var reciveLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBAction func backAction(_ sender: Any) {
        self.removeFromSuperview()
        self.clearAction(sender)
    }
    
    private var isHex:Bool = false
    
    
    public var clearReadCallBack:(()->Void)?
    public var notifyCallBack:((Bool)->Void)?
    
    override func awakeFromNib() {
        self.textView.isEditable = false
        self.textView.layer.borderWidth = 1.0
        self.textView.layer.borderColor = UIColor.blue.cgColor
        self.textView.layer.cornerRadius = 5.0
        self.textView.layoutManager.allowsNonContiguousLayout = false
    }
    
    @IBAction func setNotifyAction(_ sender: Any) {
        let btn = sender as! UISwitch
        self.notifyCallBack?(btn.isOn)
    }
    
    @IBAction func hexAction(_ sender: Any) {
        let btn = sender as! UISwitch
        self.isHex = btn.isOn
        if (btn.isOn) {
            self.textView.text = self.textView.text.unicodeScalars.filter { $0.isASCII }
                .map{String(format: "%X ", $0.value) }
                .joined()
        }
    }
    
    @IBAction func clearAction(_ sender: Any) {
        self.textView.text = ""
        self.reciveLabel.text = "接收计数：0 B"
        self.speedLabel.text =  "接收速度：0 B/S"
        self.clearReadCallBack?()
    }
    
    public func showTextContent(text:String) {
        if (self.isHex) {
            self.textView.text = text.unicodeScalars.filter { $0.isASCII }
                .map{String(format: "%X ", $0.value) }
                .joined()
        }else {
            self.textView.text = text
        }
       
    }
    
    public func showReadSpeed(totalLength:Int64, time:TimeInterval) {
    
        self.reciveLabel.text = "接收计数：\(totalLength) B"
    
        let speed = Double(totalLength) / time
        if (speed > 1000) {
            self.speedLabel.text = String.init(format: "接收速度：%0.1f KB/S", speed / 1024)
        }else {
            self.speedLabel.text = String.init(format: "接收速度：%0.1f B/S", speed)
        }
      
//        var numLines = self.textView.contentSize.height / (self.textView.font?.lineHeight ?? 1) + 1;

        let length = self.textView.text.count
        if (length > 1500) {
            self.textView.text = "";
        }
//        self.textView.contentSize = CGSize.init(width: length, height: 0)
        self.textView.selectedRange = NSRange.init(location: 0, length: length)
    }
    
    private func scrollTextViewToBottom(textView: UITextView) {
        if textView.text.count > 0 {
            let location = textView.text.count - 1
            let bottom = NSMakeRange(location, 1)
            textView.scrollRangeToVisible(bottom)
        }
    }
    

}
